#include "lua.h"
#include "lauxlib.h"
#include "app_log.h"
#include <string.h>

// Generic log function
static int log_generic(lua_State *L, const char* level_prefix) {
    int n = lua_gettop(L);
    lua_getglobal(L, "tostring");

    char log_buffer[256] = {0};
    char *buf_ptr = log_buffer;
    int remaining = sizeof(log_buffer) - 1;

    for (int i = 1; i <= n; i++) {
        lua_pushvalue(L, -1);
        lua_pushvalue(L, i);
        lua_call(L, 1, 1);

        size_t l;
        const char *s = lua_tolstring(L, -1, &l);
        if (s == NULL) {
            lua_pop(L, 1);
            continue;
        }

        if (i > 1 && remaining > 0) {
            *buf_ptr++ = '\t';
            remaining--;
        }

        int to_copy = (l < remaining) ? l : remaining;
        if (to_copy > 0) {
            memcpy(buf_ptr, s, to_copy);
            buf_ptr += to_copy;
            remaining -= to_copy;
        }
        lua_pop(L, 1);
    }

    *buf_ptr = '\0';
    app_log_printf("%s %s", level_prefix, log_buffer);
    return 0;
}

static int log_info(lua_State *L) {
    return log_generic(L, "[I/LUA]");
}

static int log_warn(lua_State *L) {
    return log_generic(L, "[W/LUA]");
}

static int log_error(lua_State *L) {
    return log_generic(L, "[E/LUA]");
}

static const luaL_Reg log_lib[] = {
    {"info", log_info},
    {"warn", log_warn},
    {"error", log_error},
    {NULL, NULL}
};

int luaopen_log(lua_State *L) {
    luaL_newlib(L, log_lib);
    return 1;
}
